package com.jackstraw.jack_base.remote_command.service.impl;

import com.jackstraw.jack_base.remote_command.config.JschConfig;
import com.jackstraw.jack_base.remote_command.entity.Conn;
import com.jackstraw.jack_base.remote_command.entity.InstallProperties;
import com.jackstraw.jack_base.remote_command.pool.entity.SessiontConnectionConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * Docker 启动
 */
@Primary
@Slf4j
@Component
public class DockerGroupControlServiceImpl extends AbstractGroupControlServiceImpl {

    public DockerGroupControlServiceImpl(JschConfig jschConfig) {
        super(jschConfig);
    }

    public final static String DOCKER_PATH = "/data/docker/";

    @Override
    public void install(InstallProperties installProperties) throws Exception {
        //docker安装需要提前设定安装目录为DOCKER_PATH
        //其余的需要手动自动目录
        installProperties.setDirectory(DOCKER_PATH);
        super.install(installProperties);
    }

    @Override
    public void installSingle(InstallProperties installProperties) throws Exception {
        String connName = installProperties.getConnName();
        //安装时间
        long startInstallTime = System.currentTimeMillis();
        log.info("当前安装环境为：{}，开始时间为：{}", connName, startInstallTime);
        this.execBeforeScript(SessiontConnectionConfig.getRootConnName(installProperties.getConnName()), installProperties);
        super.installSingle(installProperties);
        List<String> cmdList = new ArrayList<>();
        cmdList.add("cd ".concat(DOCKER_PATH));
        cmdList.add("docker-compose -f docker-compose-".concat(installProperties.getInstallName()).concat(".yml").concat(" up -d"));
        this.getJschService().execAllShell(Conn.buildExec(SessiontConnectionConfig.getRootConnName(installProperties.getConnName())), cmdList);
        //此处休眠30s，方便各种软件的初始化使用
        TimeUnit.SECONDS.sleep(30);
        this.execScript(SessiontConnectionConfig.getRootConnName(installProperties.getConnName()), installProperties);
        long endInstallTime = System.currentTimeMillis();
        log.info("当前安装环境为：{},结束时间为：{},共用时：{}毫秒", connName, endInstallTime, endInstallTime - startInstallTime);
    }

}
